import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { supabase } from '../lib/supabase'
import type { Database } from '../lib/supabase'
import { useTagManagement } from '../composables/tags'
import { useMovieTagOperations } from '../composables/tags'
import { useMovieForm, useMovieFileUpload } from '../composables/movies'
import { useDraftStore } from './useDraftStore'

type Movie = Database['public']['Tables']['movies']['Row']
type MovieInsert = Database['public']['Tables']['movies']['Insert']
type MovieUpdate = Database['public']['Tables']['movies']['Update']

export const useMovieStore = defineStore('movie', () => {
  // 标签系统
  const tagManagement = useTagManagement()
  const { 
    tags,
    fetchAllTags
  } = tagManagement

  // 计算属性 - 从标签数据中提取可用选项
  const availableGenres = computed(() => 
    tags.value.genre?.map(tag => tag.display_name) || []
  )

  const availableUniverses = computed(() => 
    tags.value.universe?.map(tag => tag.display_name) || []
  )

  const availableLanguages = computed(() => 
    tags.value.language?.map(tag => tag.display_name) || []
  )

  const availableCountries = computed(() => 
    tags.value.country?.map(tag => tag.display_name) || []
  )

  // 初始化标签系统的方法
  const initializeTags = async () => {
    console.log('开始初始化标签系统...')
    await fetchAllTags()
    console.log('标签系统初始化完成，当前标签数据:', tags.value)
    console.log('可用语言:', availableLanguages.value)
    console.log('可用宇宙:', availableUniverses.value)
    console.log('可用国家:', availableCountries.value)
    console.log('可用类型:', availableGenres.value)
  }

  // 电影标签操作
  const { setMovieSystemTags, getMovieSystemTags, extractTagValues } = useMovieTagOperations()

  // 编辑状态
  const isEditing = ref(false)
  const isUpdating = ref(false)
  const updateError = ref<string | null>(null)
  const currentMovieId = ref<number | null>(null)

  // 使用共享的表单和文件上传功能
  const movieForm = useMovieForm()
  const fileUpload = useMovieFileUpload()
  const draftStore = useDraftStore()

  // 扩展表单验证（添加上传文件验证）
  const isFormValid = computed(() => {
    return movieForm.isFormValid.value && movieForm.coverFile.value !== null
  })

  // 加载电影数据到表单（编辑模式）
  const loadMovieData = async (movieId: number) => {
    try {
      const { data: movie, error } = await supabase
        .from('movies')
        .select('*')
        .eq('id', movieId)
        .single()

      if (error) {
        throw new Error(`加载电影数据失败: ${error.message}`)
      }

      if (!movie) {
        throw new Error('电影不存在')
      }

      // 加载系统标签
      const systemTags = await getMovieSystemTags(movieId)
      const tagValues = extractTagValues(systemTags)

      // 填充表单数据
      movieForm.populateForm({
        title: movie.title || '',
        originalTitle: movie.original_title || '',
        year: movie.year || new Date().getFullYear(),
        duration: movie.duration || '',
        directors: movie.director ? movie.director.split(', ').filter(Boolean) : [],
        universe: tagValues.universe || '',
        language: tagValues.language || '',
        country: tagValues.country || '',
        rating: movie.rating || 0,
        genres: tagValues.genres || [],
        tags: movie.tags || [],
        actors: movie.actors || [],
        description: movie.description || '',
        plot: movie.plot || '',
        budget: movie.budget || '',
        box_office: movie.box_office || '',
        awards: movie.awards || [],
        trivia: movie.trivia || [],
        isAi: movie.is_ai || false
      })

      // 设置封面
      movieForm.setOriginalCoverUrl(movie.cover_url || '')
      currentMovieId.value = movieId
      isEditing.value = true

      console.log('加载电影数据完成:', {
        title: movie.title,
        coverUrl: movie.cover_url,
        originalCoverUrl: movieForm.originalCoverUrl.value,
        coverPreview: movieForm.coverPreview.value
      })

    } catch (error) {
      console.error('加载电影数据失败:', error)
      throw error
    }
  }

  // 创建电影记录（上传模式）
  const createMovie = async (coverUrl: string): Promise<Movie> => {
    const { data: { user } } = await supabase.auth.getUser()
    
    if (!user) {
      throw new Error('用户未登录')
    }

    const movieData: MovieInsert = {
      title: movieForm.form.title,
      original_title: movieForm.form.originalTitle || undefined,
      cover_url: coverUrl,
      video_url: undefined,
      rating: movieForm.form.rating,
      year: movieForm.form.year,
      duration: movieForm.form.duration,
      description: movieForm.form.description,
      plot: movieForm.form.plot || undefined,
      actors: movieForm.form.actors,
      director: movieForm.form.directors.join(', '),
      uploader_id: user.id,
      is_ai: movieForm.form.isAi,
      tags: movieForm.form.tags,
      budget: movieForm.form.budget || undefined,
      box_office: movieForm.form.box_office || undefined,
      awards: movieForm.form.awards.length > 0 ? movieForm.form.awards : undefined,
      trivia: movieForm.form.trivia.length > 0 ? movieForm.form.trivia : undefined,
      // 将封面大小写入数据库（与后端 check_cover_file_size 约束一致）
      cover_file_size: movieForm.coverFile.value?.size,
    }

    const { data, error } = await supabase
      .from('movies')
      .insert(movieData)
      .select()
      .single()

    if (error) {
      throw new Error(`创建电影记录失败: ${error.message}`)
    }

    // 添加标签关联
    await setMovieTags(data.id)

    return data
  }

  // 更新电影记录（编辑模式）
  const updateMovie = async (): Promise<Movie> => {
    if (!movieForm.isFormValid.value) {
      throw new Error('请填写所有必填字段')
    }

    if (!currentMovieId.value) {
      throw new Error('没有选择要编辑的电影')
    }

    isUpdating.value = true
    updateError.value = null

    try {
      // 上传封面图片（如果有新文件）- 优先使用已压缩的文件
      const coverUrl = await fileUpload.uploadCoverImage(
        movieForm.coverFile.value, 
        movieForm.originalCoverUrl.value,
        movieForm.compressedCoverFile.value // 传入已压缩的文件
      )
      
      // 更新电影记录
      const movieData: MovieUpdate = {
        title: movieForm.form.title,
        original_title: movieForm.form.originalTitle || undefined,
        cover_url: coverUrl,
        rating: movieForm.form.rating,
        year: movieForm.form.year,
        duration: movieForm.form.duration,
        description: movieForm.form.description,
        plot: movieForm.form.plot || undefined,
        actors: movieForm.form.actors,
        director: movieForm.form.directors.join(', '),
        is_ai: movieForm.form.isAi,
        tags: movieForm.form.tags,
        budget: movieForm.form.budget || undefined,
        box_office: movieForm.form.box_office || undefined,
        awards: movieForm.form.awards.length > 0 ? movieForm.form.awards : undefined,
        trivia: movieForm.form.trivia.length > 0 ? movieForm.form.trivia : undefined
      }

      const { data, error } = await supabase
        .from('movies')
        .update(movieData)
        .eq('id', currentMovieId.value)
        .select()
        .single()

      if (error) {
        throw new Error(`更新电影记录失败: ${error.message}`)
      }

      // 设置系统标签
      await setMovieSystemTags(currentMovieId.value, {
        genres: [...movieForm.form.genres],
        universe: movieForm.form.universe || null,
        language: movieForm.form.language || null,
        country: movieForm.form.country || null
      })

      return data
    } catch (error) {
      updateError.value = error instanceof Error ? error.message : '更新失败'
      throw error
    } finally {
      isUpdating.value = false
    }
  }

  // 为电影设置系统标签
  const setMovieTags = async (movieId: number) => {
    console.log('设置电影标签，电影ID:', movieId, '类型:', movieForm.form.genres)
    
    const success = await setMovieSystemTags(movieId, {
      genres: movieForm.form.genres,
      universe: movieForm.form.universe || null,
      language: movieForm.form.language || null,
      country: movieForm.form.country || null
    })

    if (!success) {
      throw new Error('设置电影系统标签失败')
    }
    
    console.log('电影标签设置成功')
  }

  // 删除电影
  const deleteMovie = async (): Promise<void> => {
    if (!currentMovieId.value) {
      throw new Error('没有选择要删除的电影')
    }

    try {
      const { error } = await supabase
        .from('movies')
        .delete()
        .eq('id', currentMovieId.value)

      if (error) {
        throw new Error(`删除电影失败: ${error.message}`)
      }
    } catch (error) {
      updateError.value = error instanceof Error ? error.message : '删除失败'
      throw error
    }
  }

  // 主要上传方法
  const uploadMovie = async (): Promise<Movie> => {
    if (!isFormValid.value) {
      throw new Error('请填写所有必填字段')
    }

    fileUpload.isUploading.value = true
    fileUpload.uploadError.value = null
    fileUpload.uploadProgress.value = 0

    try {
      // 上传封面图片 - 优先使用已压缩的文件
      fileUpload.uploadProgress.value = 30
      const coverUrl = await fileUpload.uploadCoverImage(
        movieForm.coverFile.value, 
        movieForm.originalCoverUrl.value,
        movieForm.compressedCoverFile.value // 传入已压缩的文件
      )
      
      // 创建电影记录
      fileUpload.uploadProgress.value = 60
      const movie = await createMovie(coverUrl!)
      
      // 设置电影系统标签
      fileUpload.uploadProgress.value = 80
      await setMovieTags(movie.id)
      
      fileUpload.uploadProgress.value = 100
      
      // 清理草稿并重置表单
      draftStore.clearUploadDraft()
      resetForm()
      
      return movie
    } catch (error) {
      fileUpload.uploadError.value = error instanceof Error ? error.message : '上传失败'
      throw error
    } finally {
      fileUpload.isUploading.value = false
    }
  }

  // 重置表单
  const resetForm = () => {
    movieForm.resetForm()
    fileUpload.resetUploadState()
    currentMovieId.value = null
    isEditing.value = false
    updateError.value = null
  }

  // （保留按需清理逻辑在调用处实现，这里不再额外导出冗余方法）

  // 路由切换时清理表单状态
  const clearFormOnRouteChange = () => {
    // 如果不是编辑模式，则完全重置表单
    if (!isEditing.value) {
      resetForm()
    }
  }

  // 初始化电影表单（根据是否传入movieId判断模式）
  const initializeMovieForm = async (movieId?: number) => {
    if (movieId) {
      // 编辑模式
      await loadMovieData(movieId)
    } else {
      // 上传模式 - 确保完全重置
      resetForm()
    }
  }

  return {
    // 状态
    isUploading: fileUpload.isUploading,
    uploadProgress: fileUpload.uploadProgress,
    uploadError: fileUpload.uploadError,
    isEditing,
    isUpdating,
    updateError,
    currentMovieId,
    
    // 表单数据
    form: movieForm.form,
    coverFile: movieForm.coverFile,
    coverPreview: movieForm.coverPreview,
    originalCoverUrl: movieForm.originalCoverUrl,
    compressedCoverFile: movieForm.compressedCoverFile, // 新增：暴露压缩文件
    
    // 临时输入
    newTag: movieForm.newTag,
    newDirector: movieForm.newDirector,
    newActor: movieForm.newActor,
    newAward: movieForm.newAward,
    newTrivia: movieForm.newTrivia,
    
    // 可用选项
    availableGenres,
    availableUniverses,
    availableLanguages,
    availableCountries,
    
    // 计算属性
    isFormValid,
    
    // 方法
    toggleGenre: movieForm.toggleGenre,
    addTag: movieForm.addTag,
    removeTag: movieForm.removeTag,
    addDirector: movieForm.addDirector,
    removeDirector: movieForm.removeDirector,
    addActor: movieForm.addActor,
    removeActor: movieForm.removeActor,
    addAward: movieForm.addAward,
    removeAward: movieForm.removeAward,
    addTrivia: movieForm.addTrivia,
    removeTrivia: movieForm.removeTrivia,
    setCoverFile: movieForm.setCoverFile,
    removeCoverFile: movieForm.removeCoverFile,
    setCompressedCoverFile: movieForm.setCompressedCoverFile, // 新增：暴露设置压缩文件的方法
    uploadMovie,
    updateMovie,
    deleteMovie,
    resetForm,
    initializeMovieForm,
    formatFileSize: fileUpload.formatFileSize,
    initializeTags,
    clearFormOnRouteChange
  }
})
